package com.appsky.drift.activity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.appsky.drift.R;
import com.appsky.drift.api.AppSkyApp;
import com.appsky.drift.api.DLog;
import com.appsky.drift.api.UserInfo;
import com.appsky.drift.api.Utils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MapView.LayoutParams;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class ChatMapModActivity extends MapActivity {

	private AppSkyApp app;

	private Button refresh;

	private MapView chatMap = null;

	private Map<Integer, View> popToUser = new HashMap<Integer, View>();

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.chat_map_mod_layout);

		app = (AppSkyApp) getApplication();
		initView();
		initMapView();
		initPopView();

	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(
				Utils.ACTION_CHAT_MESSAGE_RECEIVER);
		registerReceiver(chatMessageReceiver, filter);
		super.onStart();
	}

	@Override
	protected void onStop() {
		unregisterReceiver(chatMessageReceiver);
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	private void initView() {
		refresh = (Button) findViewById(R.id.chat_map_mod_refresh_button);

		refresh.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				initMapView();
			}
		});

	}

	private void initMapView() {
		if (chatMap == null) {
			chatMap = (MapView) findViewById(R.id.chat_map);
			chatMap.setSatellite(false);
			chatMap.setTraffic(true);
			chatMap.setStreetView(false);
		}

		setMapView();
	}

	private void setMapView() {
		GeoPoint point = new GeoPoint(app.myInfo.getLatitude(),
				app.myInfo.getLongitude());

		List<Overlay> mapOverlays = chatMap.getOverlays();

		Collection<UserInfo> infoList = app.myInfo
				.getNearbyPersonListFromHashMap();

		MyPlaceOverlay myPlace = new MyPlaceOverlay(point);

		mapOverlays.add(myPlace);
		mapOverlays.addAll(loadPersonInfo(infoList));

		MapController mapController = chatMap.getController();
		mapController.animateTo(point);
		mapController.setZoom(7);
	}

	private class MyPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		public MyPlaceOverlay(GeoPoint geoPoint) {
			this.geoPoint = geoPoint;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
					R.drawable.my_place);
			canvas.drawBitmap(bitmap, point.x, point.y, null);
		}

	}

	private class OtherPlaceOverlay extends Overlay {

		private GeoPoint geoPoint = null;

		private UserInfo info = null;

		public OtherPlaceOverlay(GeoPoint geoPoint, UserInfo info) {
			this.geoPoint = geoPoint;
			this.info = info;
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			Point point = new Point();
			Projection projection = mapView.getProjection();
			projection.toPixels(geoPoint, point);
			Bitmap bitmap = null;
			if (info.isRoomOwner()) {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.room_owner_place);
			} else if (info.isDrifting()) {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.drifting_person_place);
			} else {
				bitmap = BitmapFactory.decodeResource(getResources(),
						R.drawable.room_person_place);
			}

			canvas.drawBitmap(bitmap, point.x, point.y, null);

			Paint paint = new Paint();
			paint.setAntiAlias(true);
			paint.setTextSize(20);
			paint.setTextAlign(Align.CENTER);
			canvas.drawText(info.getNick(), point.x, point.y - 10, paint);
		}

	}

	private Collection<Overlay> loadPersonInfo(Collection<UserInfo> infoList) {
		Collection<Overlay> result = new ArrayList<Overlay>();
		Iterator<UserInfo> iterator = infoList.iterator();
		while (iterator.hasNext()) {
			UserInfo info = iterator.next();
			GeoPoint point = new GeoPoint(info.getLatitude(),
					info.getLongitude());
			OtherPlaceOverlay other = new OtherPlaceOverlay(point, info);
			result.add(other);
		}
		return result;
	}

	private void initPopView() {
		Collection<UserInfo> userList = app.myInfo
				.getNearbyPersonListFromHashMap();
		Iterator<UserInfo> iterator = userList.iterator();
		UserInfo tempUser = null;
		while (iterator.hasNext()) {
			tempUser = iterator.next();
			if (tempUser.isNotDrifting()) {
				addPopView(tempUser);
			}
		}
		addPopView(app.myInfo);// 这里还要把自己添加进去，所以再加一句
	}

	private void addPopView(UserInfo user) {
		RelativeLayout popView = (RelativeLayout) getLayoutInflater().inflate(
				R.layout.chat_pop_layout, null);
		GeoPoint geo = new GeoPoint((user.getLatitude()), (user.getLongitude()));
		LayoutParams lp = new MapView.LayoutParams(
				MapView.LayoutParams.WRAP_CONTENT,
				MapView.LayoutParams.WRAP_CONTENT, geo,
				MapView.LayoutParams.BOTTOM_CENTER);
		chatMap.addView(popView, lp);
		popView.setVisibility(View.INVISIBLE);
		popToUser.put(user.getUserId(), popView);
	}

	private BroadcastReceiver chatMessageReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			DLog.i("MapMod收到聊天消息");
			String string = intent.getStringExtra("json");
			JSONObject json = JSONObject.parseObject(string);
			int id = json.getIntValue("id");
			String content = json.getString("content");
			RelativeLayout pop = (RelativeLayout) popToUser.get(id);
			pop.setVisibility(View.VISIBLE);
			TextView textView = (TextView) pop.findViewById(R.id.pop_chat_text);
			textView.setText(content);
		}
	};

}
